package dao

import (
	"errors"
	"github.com/go-sql-driver/mysql"
	"gorm.io/gorm"
	"time"
)

var ErrDuplicateEmail = errors.New("邮箱已存在")

type UserDao struct {
	db *gorm.DB
}

func NewUserDao(db *gorm.DB) *UserDao {
	return &UserDao{
		db: db,
	}
}

func InitTable(db *gorm.DB) error {
	return db.AutoMigrate(&User{})
}

type User struct {
	Id           int64  `gorm:"primaryKey,autoIncrement"`
	Email        string `gorm:"unique"`
	Password     string
	NickName     string
	BirthDay     int64
	Introduction string
	Ctime        int64
	Utime        int64
}

func (userDao *UserDao) Insert(user User) error {
	now := time.Now().UnixMilli()
	user.Ctime = now
	user.Utime = now
	err := userDao.db.Create(&user).Error
	// 判断错误类型是否是唯一键冲突，如果是则返回唯一键冲突异常
	var mysqlErr *mysql.MySQLError
	if errors.As(err, &mysqlErr) {
		if mysqlErr.Number == 1062 {
			return ErrDuplicateEmail
		}
	}
	return err
}

func (userDao *UserDao) FindByEmail(email string) (User, error) {
	var user User
	err := userDao.db.First(&user, "email = ?", email).Error
	return user, err
}

func (userDao *UserDao) FindById(id int64) (User, error) {
	var user User
	err := userDao.db.First(&user, "id = ?", id).Error
	return user, err
}

func (userDao *UserDao) Update(user User) (int64, error) {
	now := time.Now().UnixMilli()
	user.Utime = now
	db := userDao.db.Updates(&user)
	return db.RowsAffected, db.Error
}
